/* 博客文章系统路由
 * @Author: Leil 
 * @Date: 2018-08-24 14:45:47 
 * @Last Modified by: Leil
 * @Last Modified time: 2018-09-05 22:04:05
 */
const express = require('express')
const router = express.Router()
const checkLogin = require('../middleware/check').checkLogin
const postService = require('../service/postService')
const common = require('../lib/common')

router.use(checkLogin)

router.get('/', function (req, res) {
    res.render('admin/post')
})

router.get('/:postId', function(req, res) {
    // console.log(req.params)
    let postId = req.params.postId
    postService.getPostById(postId)
        .then(post => {
            res.send(post)
            return
        })
        .catch(error => {
            console.log(error.errmsg)
        })
})

router.post('/', function (req, res) {
    console.log(req)
    const postId = req.fields.postId
    const title = req.fields.title
    const imgPath = req.fields.imgPath
    const text = req.fields.postText
    const postDescription = req.fields.postDescription
    const categoryId = req.fields.categoryId
    const categoryName = req.fields.categoryName
    console.log(common.formatDate("yyyy-MM-dd hh:mm:ss", new Date()))
    let postInfo = {
        title: title,
        imgPath: imgPath,
        text: text,
        postDescription: postDescription,
        categoryId: categoryId,
        categoryName: categoryName,
        updateTime: common.formatDate("yyyy-MM-dd hh:mm:ss", new Date())
    }
    if (postId) {
        // 更新
        postService.updatePostById(postId, postInfo)
            .then(data => {
                res.send(data)
                return
            })
            .catch(error => console.log(error.errmsg))
    } else {
        // 添加
        postService
            .addOnePost(postInfo)
            .then(data => {
                res.send(data)
                return
            })
            .catch(error => console.log(error.errmsg))
    }
    
})

module.exports = router